package com.lowca.news.web.listener;

import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import static com.lowca.news.constant.Constants.RoleMeta;
import static com.lowca.news.constant.Constants.DEVELOPER_USERNAME;
import static com.lowca.news.constant.Constants.DEVELOPER_PASSWORD;
import static com.lowca.news.constant.Constants.DEVELOPER_EMAIL;

import com.lowca.news.entity.Role;
import com.lowca.news.entity.User;
import com.lowca.news.service.RoleService;
import com.lowca.news.service.UserService;
import com.lowca.news.util.Collections3;
import com.lowca.news.util.Exceptions;

/**
 * 检查系统和做准备工作的监听器，它的优先级低于spring，可以访问spring上下文
 * 
 * @author konglz
 * 
 */
public class CheckAndPreparedListener implements ServletContextListener {

	private ApplicationContext applicationContext = null;
	private static final Log log = LogFactory
			.getLog(CheckAndPreparedListener.class);

	@Override
	public void contextInitialized(ServletContextEvent sce) {
		log.info("初始化系统环境");
		ServletContext application = sce.getServletContext();
		applicationContext = WebApplicationContextUtils
				.getWebApplicationContext(application);
		onInitialize(applicationContext, application);
		log.info("系统环境初始化完毕");
	}

	/**
	 * 系统初始化的若干工作
	 * 
	 * @param applicationContext2
	 * @param application
	 */
	protected void onInitialize(ApplicationContext springContext,
			ServletContext application) {
		// 在这里只能使用service而不能直接使用dao，因为事务是基于service的，dao没有事务支持，在hibernate4中会导致出错。
		log.info("检查系统用户角色是否正常");
		RoleService roleService = springContext.getBean(RoleService.class);
		Set<Role> needCreateRoles = new HashSet<Role>();
		for (RoleMeta roleMeta : RoleMeta.values()) {
			String name = roleMeta.getName();
			boolean hasRole = roleService.existRoleByName(name);
			if (!hasRole) {
				Role role = new Role();
				role.setName(name);
				role.setDescription(roleMeta.getDescription());
				needCreateRoles.add(role);
			}
		}
		if (needCreateRoles.size() > 0) {
			roleService.createRoles(needCreateRoles);
			@SuppressWarnings("unchecked")
			List<String> names = Collections3.extractToList(needCreateRoles,
					"name");
			log.info(names + "不存在，创建这些角色");
		}
		log.info("系统用户角色检查完毕");
		log.info("检查开发者用户是否存在");
		// 检查开发者用户是否存在
		UserService userService = springContext.getBean(UserService.class);
		if (!userService.existUserByUsername(DEVELOPER_USERNAME)) {
			User developer = new User();
			developer.setUsername(DEVELOPER_USERNAME);
			developer.setPassword(DEVELOPER_PASSWORD);
			developer.setEmail(DEVELOPER_EMAIL);
			developer.setRegisterTime(new Date());
			developer.setRegisterIp("127.0.0.1");
			try {
				userService.createUser(developer);
			} catch (Exception e) {
				Exceptions.unchecked(e);
			}
			log.info("开发者角色不存在，创建一个开发者角色");
			roleService.addRoleToUser(developer, RoleMeta.DEVELOPER.getName());
			log.info("赋予此角色开发者权限");
		}
		log.info("开发者用户检查完毕");
	}

	@Override
	public void contextDestroyed(ServletContextEvent sce) {
		// TODO Auto-generated method stub

	}

}